using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;


/// <summary>
/// Summary description for Encryption
/// </summary>
public class Encryption
{
    string TamperProofKey = "YourUglyHardCodedKeyLike-alksfjlkasjfl3425";
	public Encryption()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    private string TamperProofStringEncode(string value, string key)
    {
        System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));
        return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(value)) + '-' + Convert.ToBase64String(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(value)));
    }

    //Function to decode the string 
    //Throws an exception if the data is corrupt 
    public string TamperProofStringDecode(string value, string key)
    {
        string dataValue = "";
        string calcHash = "";
        string storedHash = "";
     
        System.Security.Cryptography.MACTripleDES mac3des = new System.Security.Cryptography.MACTripleDES();
        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        mac3des.Key = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key));

        try
        {
            
            dataValue = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[0]));
            storedHash = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String(value.Split('-')[1]));
            calcHash = System.Text.Encoding.UTF8.GetString(mac3des.ComputeHash(System.Text.Encoding.UTF8.GetBytes(dataValue)));

            if (storedHash != calcHash)
            {
                //Data was corrupted 

                throw new ArgumentException("Hash value does not match");
                //This error is immediately caught below 
            }
        }
        catch (Exception)
        {
            throw new ArgumentException("Invalid TamperProofString");
        }

        return dataValue;

    }
    public string QueryStringEncode(string value)
    {

        return HttpUtility.UrlEncode(TamperProofStringEncode(value, TamperProofKey));
    }

    public string QueryStringDecode(string value)
    {
        return TamperProofStringDecode(value, TamperProofKey);
    } 

}
